package com.tt.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 创建WebSocket握手
 * socket回话拦截器
 * 2022/3/6 - 18:34
 */
public class MyHandshakeInterceptor extends HttpSessionHandshakeInterceptor
{
    // 握手前
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {


        System.out.println("++++++++++++++++ HandshakeInterceptor: beforeHandshake  ++++++++++++++"+attributes);

        if(request instanceof ServletServerHttpRequest){
            HttpServletRequest httpRequest = ((ServletServerHttpRequest) request).getServletRequest();
            //从header中获取token
           // String token = httpRequest.getHeader(LOGIN_TOKEN_KEY);
            //如果header中不存在token，则从参数中获取token
//            if (StringUtils.isBlank(token)) {
//                token = httpRequest.getParameter(LOGIN_TOKEN_KEY);
//            }

//            //token为空
//            if (StringUtils.isBlank(token)) {
//                return false;
//            }
//
//            //查询token信息
//            TokenEntity tokenEntity = tokenService.queryByToken(token);
//            if (tokenEntity == null) {
//                return false;
//            }
//
//            attributes.put(LOGIN_USER_KEY,tokenEntity.getConsumerId());
        }

        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    // 握手后
    @Override
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex)
    {

    }
}
